package com.aatattoo.light_food_service.controller;

import com.aatattoo.light_food_service.entity.*;
import com.aatattoo.light_food_service.enumeration.ConstantType;
import com.aatattoo.light_food_service.service.*;
import com.aatattoo.light_food_service.utils.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author aatattoo
 * @Date 2021/12/13 11:52 上午
 * @msg:
 */



@Controller
@RequestMapping("/function")
@ResponseBody
public class DynamicFunctionController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CommentService commentService;
    @Autowired
    ReplyService replyService;
    @Autowired
    private RemindService remindService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private DynamicTagFollowService dynamicTagFollowService;
    @Autowired
    private DynamicTagService dynamicTagService;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private MappingTagService mappingTagService;
    @Autowired
    private DynamicImgService dynamicImgService;
    @Autowired
    private FoodService foodService;

    /**
     * 模糊查询 动态
     * @param type 0-动态
     *             1-标签
     *             2-用户
     * @param pageNum
     * @param text
     * @param token
     * @return
     */
    @GetMapping("/query/{type}/{pageNum}/{text}")
    public Map<String,Object> getQueryDynamic(@PathVariable("type")int type,@PathVariable("pageNum")int pageNum,@PathVariable("text")String  text,@RequestHeader("token")String token){
//       0:动态 1：话题（标签） 2：用户
        // 设置分页查询参数
        //pageSize:一页记录的数据量
        PageHelper.startPage(pageNum,10);
        int userId = tokenService.analysisUserId(token);
        Map<String,Object> mapData =new LinkedHashMap<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        switch (type){
            case 0:
                List<Dynamic> dynamics = dynamicService.fuzzyQuery(text);
                mapData=pagingQuery(dynamics,userId,userId,1);
                break;
            case 1:
                List<DynamicTag> dynamicTagList = dynamicTagService.fuzzyQuery(text);
                PageInfo pageInfo1 = new PageInfo(dynamicTagList);
                pageMap.put("pageCount",pageInfo1.getPages());
                pageMap.put("pageNumber",pageInfo1.getPageNum());
                mapData.put("page",pageMap);
                DynamicTagFollow dynamicTagFollow = new DynamicTagFollow();
                dynamicTagFollow.setUserId(userId);
                List<Object> tagList=new ArrayList<>();
                pageInfo1.getList().forEach(tag->{
                    DynamicTag dynamicTag=(DynamicTag)tag;
                    Map<String,Object> tagMap=new LinkedHashMap<>();
                    tagMap.put("id",dynamicTag.getId());
                    tagMap.put("content",dynamicTag.getContent());
                    dynamicTagFollow.setTagId(dynamicTag.getId());
                    int tableFollowTag = dynamicTagFollowService.isTableFollowTag(dynamicTagFollow);
                    tagMap.put("follow",tableFollowTag!=0);
                    tagList.add(tagMap);
                });
                mapData.put("tag",tagList);
                break;
            case 2:
                List<User> userList = userService.fuzzyQuery(text);
                PageInfo pageInfo = new PageInfo(userList);
                pageMap.put("pageCount",pageInfo.getPages());
                pageMap.put("pageNumber",pageInfo.getPageNum());
                mapData.put("page",pageMap);
                List<Object> userDataList = new ArrayList<>();
                pageInfo.getList().forEach(userPage->{
                    User user=(User)userPage;
                    Map<String,Object> userMap=new LinkedHashMap<>();
                    //获取发布动态的用户信息
                    UserFollow userFollow=new UserFollow();
                    userFollow.setFollowId(user.getId());
                    userFollow.setFansId(userId);
                    int follow = userFollowService.findFollowByBothId(userFollow);
                    int mutual = userFollowService.mutualAttentionFindById(userFollow);
                    userMap.put("id",user.getId());
                    userMap.put("name",user.getName());
                    userMap.put("gender",user.getGender());
                    userMap.put("avatar",user.getAvatar());
                    userMap.put("follow", follow != 0);
                    userMap.put("mutualAttention",mutual!=0);
                    userDataList.add(userMap);
                });
                mapData.put("user",userDataList);
                break;
            default:
                break;
        }
        return mapData;
    }

    /**
     * 获取所有标签
     * @param type 获取标签的类型
     *             0-我关注的标签
     *             1-日常分享
     *             2-目标打卡
     *             3-用户自定义
     * @return
     */
    @GetMapping("/allTag/{type}/{pageNum}")
    public Map<String, Object> getAllTag(@PathVariable("type")int type, @PathVariable("pageNum")int pageNum, @RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        PageHelper.startPage(pageNum, 10);
        List<Object> tagList=new ArrayList<>();
        Map<String,Object> mapData=new LinkedHashMap<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        switch (type){
            case 0:
                List<Integer> followTagId = dynamicTagFollowService.getFollowTagId(userId);
                PageInfo pageInfo = new PageInfo(followTagId);
                pageMap.put("pageCount",pageInfo.getPages());
                pageMap.put("pageNumber",pageInfo.getPageNum());
                mapData.put("page",pageMap);
                pageInfo.getList().forEach(list->{
                    int tagId=(int)list;
                    Map<String,Object> tagMap=new LinkedHashMap<>();
                    DynamicTag tagById = dynamicTagService.findById(tagId);
                    tagMap.put("id",tagById.getId());
                    tagMap.put("content",tagById.getContent());
                    tagMap.put("follow",true);
                    tagList.add(tagMap);
                });
                mapData.put("tag",tagList);
                break;
            case 1:
            case 2:
            case 3:
                List<DynamicTag> dynamicTagList = dynamicTagService.findAll(type);
                PageInfo pageInfo1 = new PageInfo(dynamicTagList);
                pageMap.put("pageCount",pageInfo1.getPages());
                pageMap.put("pageNumber",pageInfo1.getPageNum());
                mapData.put("page",pageMap);
                DynamicTagFollow dynamicTagFollow = new DynamicTagFollow();
                dynamicTagFollow.setUserId(userId);
                pageInfo1.getList().forEach(tag->{
                    DynamicTag dynamicTag=(DynamicTag)tag;
                    Map<String,Object> tagMap=new LinkedHashMap<>();
                    tagMap.put("id",dynamicTag.getId());
                    tagMap.put("content",dynamicTag.getContent());
                    dynamicTagFollow.setTagId(dynamicTag.getId());
                    int tableFollowTag = dynamicTagFollowService.isTableFollowTag(dynamicTagFollow);
                    tagMap.put("follow",tableFollowTag!=0);
                    tagList.add(tagMap);
                });
                mapData.put("tag",tagList);
                break;
            default:
                break;
        }
        return mapData;
    }

    /**
     * 取消关注标签
     * @param dynamicTagFollow  将要取消关注的标签ID
     * @param token 用户token
     * @return
     */
    @PostMapping("/tagUnFollow")
    public int tagUnFollow(@RequestBody DynamicTagFollow dynamicTagFollow,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        dynamicTagFollow.setUserId(userId);
        return dynamicTagFollowService.unFollowTag(dynamicTagFollow);
    }
    /**
     * 标签关注功能
     * @param dynamicTagFollow   关注的标签id
     * @param token 用户token
     * @return  是否关注成功
     */
    @PostMapping("/tagFollow")
    public int tagFollow(@RequestBody DynamicTagFollow dynamicTagFollow,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        dynamicTagFollow.setUserId(userId);
        return dynamicTagFollowService.followTag(dynamicTagFollow);
    }

    @PostMapping("/dislike")
    public int dislikeDynamic(@RequestBody Like like,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        like.setUserId(userId);
        return likeService.deleteLike(like);
    }
    @PostMapping("/like")
    public int likeDynamic(@RequestBody Like like,@RequestHeader("token")String token){
        int userId = tokenService.analysisUserId(token);
        like.setUserId(userId);

        return likeService.addLike(like);
    }

    @GetMapping("/comments/{dynamicId}/{pageNum}")
    public Map<String, Object> getComent(@PathVariable("dynamicId")int dynamicId, @PathVariable("pageNum")int pageNum, @RequestHeader("token")String token){
        PageHelper.startPage(pageNum,15);
        List<Object> comentList=new ArrayList<>();
        //检查是否有评论，有:查找评论，无直接返回空列表
        List<Comment> comments = commentService.findByDynamicId(dynamicId);
        PageInfo pageInfo = new PageInfo( comments );
        Map<String,Object> mapData=new LinkedHashMap<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
        int commentSize=comments.size();
        if (commentSize!=0){
            int userId = tokenService.analysisUserId(token);
            pageInfo.getList().forEach(list -> {
                Comment comment=(Comment)list;
                Map<String,Object> commetMap=new LinkedHashMap<>();
                commetMap.put("user",userService.getUserMap(comment.getUserId()));
                commetMap.put("id",comment.getId());
                commetMap.put("content",comment.getContent());
                //点赞字段
                Like comentLike=new Like();
                comentLike.setUserId(userId);
                comentLike.setType(ConstantType.LIKE_COMMENT.getType());
                comentLike.setParentId(comment.getId());
                commetMap.put("like",likeService.checkLike(comentLike)!=0);
                commetMap.put("countLike",likeService.countLike(comentLike));
                List<Object> commentRemindList=new ArrayList<>();
                if (comment.getHaveRemind()==ConstantType.COMMENT_REMIND.getType()){
                    Remind forReminds=new Remind();
                    forReminds.setType(ConstantType.REMIND_COMMENT.getType());
                    forReminds.setParentID(comment.getId());
                    List<Remind> reminds = remindService.getAllByParentId(forReminds);
                    reminds.forEach(remind -> {
                        User user = userService.fingById(remind.getPassiveId());
                        Map<String,Object> remindMap=new LinkedHashMap<>();
                        remindMap.put("id",remind.getPassiveId());
                        remindMap.put("userName",user.getName());
                        remindMap.put("order",remind.getOrder());
                        commentRemindList.add(remindMap);
                    });
                }
                commetMap.put("remind",commentRemindList);
                //子评论，@的用户信息
                List<Object> replyList=new ArrayList<>();
                if(comment.getHaveReply()==ConstantType.COMMENT_REPLY.getType()){
                    List<Reply> replies = replyService.findeByComentId(comment.getId());
                    replies.forEach(reply -> {
                        Map<String,Object> replyMap=new LinkedHashMap<>();
                        replyMap.put("user",userService.getUserMap(reply.getActiveId()));
                        replyMap.put("replyUser",userService.getUserMap(reply.getPassiveId()));
                        replyMap.put("id",reply.getId());
                        replyMap.put("content",reply.getContent());
                        //点赞字段
                        Like replyLike=new Like();
                        replyLike.setUserId(userId);
                        replyLike.setType(ConstantType.LIKE_REPLY.getType());
                        replyLike.setParentId(reply.getId());
                        replyMap.put("like",likeService.checkLike(replyLike)!=0);
                        replyMap.put("countLike",likeService.countLike(replyLike));
                        List<Object> remindList=new ArrayList<>();
                        if (reply.getHaveRemind()==ConstantType.COMMENT_REMIND.getType()){
                            Remind forReminds=new Remind();
                            forReminds.setType(ConstantType.REMIND_REPLY.getType());
                            forReminds.setParentID(reply.getId());
                            List<Remind> reminds = remindService.getAllByParentId(forReminds);
                            reminds.forEach(remind -> {
                                User user = userService.fingById(remind.getPassiveId());
                                Map<String,Object> remindMap=new LinkedHashMap<>();
                                remindMap.put("id",remind.getPassiveId());
                                remindMap.put("userName",user.getName());
                                remindMap.put("order",remind.getOrder());
                                remindList.add(remindMap);
                            });
                        }
                        replyMap.put("remind",remindList);
                        replyMap.put("createTime", TimeUtil.timestampFormat(reply.getCreateTime()));
                        replyList.add(replyMap);
                    });
                }
                commetMap.put("reply",replyList);
                commetMap.put("createTime",TimeUtil.timestampFormat(comment.getCreateTime()));
                comentList.add(commetMap);
            });
        }
        mapData.put("comment",comentList);
        return mapData;
    }

    @PostMapping("/dropComment")
    public int deleteComment(@RequestBody Comment comment){
        replyService.deleteByComent(comment.getId());
        return commentService.deleteById(comment.getId());
    }

    @PostMapping("/dropReply")
    public int deleteReply(@RequestBody Reply reply){
        return replyService.deleteById(reply.getId());
    }

    @PostMapping("/comment")
    public int addComment(@RequestBody CommentRelease commentRelease, @RequestHeader("token")String token){
        Comment comment =new Comment();
        int userId = tokenService.analysisUserId(token);
        int remindSize=commentRelease.getRemind().size();
        comment.setDynamicId(commentRelease.getDynamicId());
        comment.setUserId(userId);
        comment.setContent(commentRelease.getContent());
        comment.setHaveReply(ConstantType.COMMENT_UNREPLY.getType());
        comment.setHaveRemind(remindSize==0? ConstantType.COMMENT_UNREMIND.getType():ConstantType.COMMENT_REMIND.getType());
        int commentId = commentService.addComment(comment);
        if (remindSize!=0){
            commentRelease.getRemind().forEach(passiveId->{
                Remind remind=new Remind();
                remind.setActiveId(userId);
                remind.setPassiveId(passiveId);
                remind.setType(ConstantType.REMIND_COMMENT.getType());
                remind.setParentID(commentId);
                remind.setOrder(commentRelease.getRemind().indexOf(passiveId)+1);
                remindService.addRemind(remind);
            });
        }
        return commentId;
    }

    @PostMapping("/reply")
    public int addReply(@RequestBody ReplyRelease replyRelease,@RequestHeader("token")String token){
        Reply reply=new Reply();
        int userId = tokenService.analysisUserId(token);
        int remindSize=replyRelease.getRemind().size();
        reply.setCommentId(replyRelease.getCommentId());
        reply.setActiveId(userId);
        reply.setPassiveId(replyRelease.getUserId());
        reply.setContent(replyRelease.getContent());
        reply.setHaveRemind(remindSize==0? ConstantType.COMMENT_UNREMIND.getType():ConstantType.COMMENT_REMIND.getType());
        int replyId = replyService.addReply(reply);
        Comment comment=new Comment();
        comment.setId(reply.getCommentId());
        comment.setHaveReply(ConstantType.COMMENT_REPLY.getType());
        commentService.updataHaveReply(comment);
        if (remindSize!=0){
            replyRelease.getRemind().forEach(passiveId->{
                Remind remind=new Remind();
                remind.setActiveId(userId);
                remind.setPassiveId(passiveId);
                remind.setType(ConstantType.REMIND_REPLY.getType());
                remind.setParentID(replyId);
                remind.setOrder(replyRelease.getRemind().indexOf(passiveId)+1);
                remindService.addRemind(remind);
            });
        }
        return replyId;
    }

    /**
     *
     * @param dynamicList
     * @param myId
     * @param type 0,1-每条动态都携带用户参数
     *             2-我的动态，只显示一天用户参数，我的
     *             3-只显示一条用户参数（详细）其他用户

     * @return
     */
    private  Map<String, Object> pagingQuery(List<Dynamic> dynamicList,int myId,int othUserId,int type){
        // 封装分页查询结果到 PageInfo 对象中以获取相关分页信息
        PageInfo pageInfo = new PageInfo( dynamicList );
        Map<String,Object> mapData=new LinkedHashMap<>();
        List<Object> mapList=new ArrayList<>();
        Map<String,Object> pageMap=new LinkedHashMap<>();
        pageMap.put("pageCount",pageInfo.getPages());
        pageMap.put("pageNumber",pageInfo.getPageNum());
        mapData.put("page",pageMap);
//       获取个人动态或指定用户动态，只需要提供一次用户信息
        Map<String,Object> userMap=new LinkedHashMap<>();
        if (type==3){
            if (!mapData.containsKey("user")){
                //获取发布动态的用户信息
                User dynamicUser = userService.fingById(othUserId);
                UserFollow userFollow=new UserFollow();
                userFollow.setFollowId(othUserId);
                userFollow.setFansId(myId);
                int follow = userFollowService.findFollowByBothId(userFollow);
                int mutual = userFollowService.mutualAttentionFindById(userFollow);
                int countFollow = userFollowService.countFollowById(othUserId);
                int countFans = userFollowService.countFansById(othUserId);
                int countDynamic = dynamicService.countDynamicByUserId(othUserId);
                userMap.put("id",dynamicUser.getId());
                userMap.put("name",dynamicUser.getName());
                userMap.put("gender",dynamicUser.getGender());
                userMap.put("avatar",dynamicUser.getAvatar());
                userMap.put("follow", follow != 0);
                userMap.put("mutualAttention",mutual!=0);
                userMap.put("countFollow",countFollow);
                userMap.put("countFans",countFans);
                userMap.put("dynamic",countDynamic);
                mapData.put("user",userMap);
            }
        }
        if (type==2){
            if (!mapData.containsKey("user")){
                //获取发布动态的用户信息
                mapData.put("user",userService.getUserMap(myId));
            }
        }
        pageInfo.getList().forEach(list -> {
            Dynamic dynamic=(Dynamic)list;
            List<Object> imgList=new ArrayList<>();
            List<Object> tagList=new ArrayList<>();
            List<Object> remindList=new ArrayList<>();
            Map<String,Object> forwadrMap=new HashMap<>();
            Map<String,Object> map=new LinkedHashMap<>();
            Map<String,Object> othUserMap=new LinkedHashMap<>();
            if (type==1||type==0){
                //            每条动态都需要携带用户参数
                //获取发布动态的用户信息
                User dynamicUser = userService.fingById(dynamic.getUserId());
                UserFollow userFollow=new UserFollow();
                userFollow.setFollowId(dynamic.getUserId());
                userFollow.setFansId(myId);
                int follow = userFollowService.findFollowByBothId(userFollow);
                int mutual = userFollowService.mutualAttentionFindById(userFollow);
                othUserMap.put("id",dynamicUser.getId());
                othUserMap.put("name",dynamicUser.getName());
                othUserMap.put("avatar",dynamicUser.getAvatar());
                othUserMap.put("follow", follow != 0);
                othUserMap.put("mutualAttention",mutual!=0);
                map.put("user",othUserMap);
            }
            map.put("id",dynamic.getId());
            map.put("content",dynamic.getContent());
            if (dynamic.getHaveImg()== ConstantType.DYNAMIC_IMG.getType()){
                List<DynamicImg> dynamicImgs = dynamicImgService.findAllByDynamicID(dynamic.getId());
                dynamicImgs.forEach(dynamicImg -> {
                    Map<String,Object> imgMap=new LinkedHashMap<>();
                    imgMap.put("id",dynamicImg.getId());
                    imgMap.put("address",dynamicImg.getAddress());
                    imgMap.put("drder",dynamicImg.getOrder());
                    imgList.add(imgMap);
                });
            }
            if (dynamic.getHaveTag()==ConstantType.DYNAMIC_TAG.getType()){
                List<MappingTag> mappingTags = mappingTagService.findAllByDynamicId(dynamic.getId());
                mappingTags.forEach(mappingTag -> {
                    Map<String,Object> tagMap=new LinkedHashMap<>();
                    DynamicTag dynamicTag = dynamicTagService.findById(mappingTag.getTagId());
                    tagMap.put("id",dynamicTag.getId());
                    tagMap.put("content",dynamicTag.getContent());
                    tagMap.put("order",mappingTag.getOrder());
                    tagList.add(tagMap);
                });
            }
            if (dynamic.getHaveRemind()==ConstantType.DYNAMIC_REMIND.getType()){
                Remind forReminds=new Remind();
                forReminds.setType(ConstantType.REMIND_DYNAMIC.getType());
                forReminds.setParentID(dynamic.getId());
                List<Remind> reminds = remindService.getAllByParentId(forReminds);
                reminds.forEach(remind -> {
                    User user = userService.fingById(remind.getPassiveId());
                    Map<String,Object> remindMap=new LinkedHashMap<>();
                    remindMap.put("id",remind.getPassiveId());
                    remindMap.put("userName",user.getName());
                    remindMap.put("order",remind.getOrder());
                    remindList.add(remindMap);
                });
            }
            if (dynamic.getForward() != 0){
                int id = dynamic.getForward();
                Recipes recipes = foodService.getRecipes(id);
                forwadrMap.put("id",recipes.getId());
                forwadrMap.put("name",recipes.getName());
                forwadrMap.put("photo",recipes.getPhoto());
                forwadrMap.put("more",recipes.getMore());
            }
            map.put("img",imgList);
            map.put("tag",tagList);
            map.put("remind",remindList);
            map.put("type",dynamic.getType());
            map.put("forward",forwadrMap);
            //动态喜欢、评论、收藏的数量
//            喜欢
            Like like=new Like();
            like.setType(1);
            like.setParentId(dynamic.getId());
            like.setUserId(myId);
            int dynamicLike = likeService.countLike(like);
//            评论
            int commentCount=0;
            commentCount = commentCount + commentService.countComment(dynamic.getId());
            List<Integer> idList = commentService.findByDynamicIdForId(dynamic.getId());
            commentCount += idList.stream().mapToInt(id -> replyService.countReply(id)).sum();
//            收藏
            Collect collect=new Collect();
            collect.setType(2);
            collect.setParentId(dynamic.getId());
            collect.setUserId(myId);
            int collectCount = foodService.countCollect(collect);
            map.put("like",dynamicLike);
            map.put("is_like",likeService.checkLike(like) == 1);
            map.put("comment",commentCount);
            map.put("collection",collectCount);
            map.put("is_collection",foodService.checkCollect(collect)==1);
            map.put("createTime", TimeUtil.timestampFormat(dynamic.getCreateTime()));
            mapList.add(map);
        });
        mapData.put("dynamic",mapList);
        return mapData;
    }


}
